<template>
  <receipt-core
    @clear-open-json="clearOpenJson"
    @pose-edit-json="poseEditJson"
    @pose-submit-json="poseSubmitJson"
    @pose-sub-details-edit-json="poseSubDetailsEditJson"
    @add-row-sub="addRowSub"
    @data-format="dataFormat"
    @delete-row-sub="deleteRowSub"
    @json-format="jsonFormat"
    ref="idJsonItemsRefs"
    :edit-btn-visible="false"
    :open-details-sub-visible="true"
    receipts-name="order_receipt"
    receipts-type="订单"
    receipts-no="002"
    :approve-name="props.approveName"
  >
    //弹窗的主表的插入的idJson信息
    <template #idJsonSlot>
      <el-row>
        <el-col :span="8">
          <el-form-item
            label="客户名称："
            prop="customerName"
            label-width="120px"
          >
            <autocomplete-input
              v-model="idJsonItems.customerName"
              :value-key="selectedPropMap.selectedOriginProp"
              @get-record="getRecords"
            ></autocomplete-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="编制人："
            prop="preparationPerson"
            label-width="120px"
          >
            <el-input v-model="idJsonItems.preparationPerson"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="编制日期："
            prop="preparationDate"
            label-width="120px"
          >
            <el-date-picker
              v-model="idJsonItems.preparationDate"
              type="date"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item
            label="单位负责人："
            prop="unitLeader"
            label-width="120px"
          >
            <el-input v-model="idJsonItems.unitLeader"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核人：" prop="auditor" label-width="120px">
            <el-input v-model="idJsonItems.auditor"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="复核人：" prop="reviewer" label-width="120px">
            <el-input v-model="idJsonItems.reviewer"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
    //弹窗的子表的表格的插入的subJson信息
    <template #subJson>
      <el-table-column align="center" label="自制件名称" min-width="180">
        <template #default="scope">
          <autocomplete-input
            v-model="subJsonItems[scope.$index].homemadeName"
            :value-key="selectedPropMapSub.selectedOriginProp"
            @get-record="autocompleteInputEventSub.getRecords"
          ></autocomplete-input>
        </template>
      </el-table-column>
      <el-table-column align="center" label="型号" width="180" min-width="160">
        <template #default="scope">
          <el-input v-model="subJsonItems[scope.$index].model"></el-input>
        </template>
      </el-table-column>
      <el-table-column align="center" label="数量" width="180" min-width="160">
        <template #default="scope">
          <el-input v-model="subJsonItems[scope.$index].quantity"></el-input>
        </template>
      </el-table-column>
      <el-table-column align="center" label="单位" width="180" min-width="160">
        <template #default="scope">
          <el-input v-model="subJsonItems[scope.$index].unit"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="已完成数量"
        width="180"
        min-width="160"
      >
        <template #default="scope">
          <el-input
            v-model="subJsonItems[scope.$index].completedQuantity"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="期望交货日期"
        width="250"
        min-width="160"
      >
        <template #default="scope">
          <el-date-picker
            v-model="subJsonItems[scope.$index].expectedDeliveryDate"
            type="date"
            placeholder="请选择日期"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="施工区间"
        width="180"
        min-width="160"
      >
        <template #default="scope">
          <el-input
            v-model="subJsonItems[scope.$index].constructionSection"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="实际交付日期"
        width="250"
        min-width="160"
      >
        <template #default="scope">
          <el-date-picker
            v-model="subJsonItems[scope.$index].actualDeliveryDate"
            type="date"
            placeholder="请选择日期"
          />
        </template>
      </el-table-column>
    </template>
    //子表展开细节时插入的subJson信息
    <template #subJsonDetails>
      <el-row>
        <el-col :span="8">
          <el-form-item label="自制件名称：" label-width="120px">
            <el-input
              v-model="subJsonDetailsItems.homemadeName"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="型号：" label-width="120px">
            <el-input v-model="subJsonDetailsItems.model" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="数量：" label-width="120px">
            <el-input
              v-model="subJsonDetailsItems.quantity"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" plain @click="addRowSubMaterial"
          >增加
        </el-button>
      </el-form-item>
    </template>
    <template #subJsonDetailsTable>
      <el-table :data="OrderReceiptSubMaterial" max-height="580px">
        <el-table-column
          align="center"
          type="index"
          prop="no"
          label="序号"
          fixed="left"
          width="60"
          min-width="60"
        />
        <el-table-column
          align="center"
          prop="materialCategory"
          label="物料类别"
          width="150"
          min-width="150"
        >
          <template #default="scope">
            <el-input v-model="scope.row.materialCategory"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="materialName"
          label="物料名"
          width="150"
          min-width="150"
        >
          <template #default="scope">
            <el-input v-model="scope.row.materialName"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="materialNo"
          label="物料编号"
          width="150"
          min-width="150"
        >
          <template #default="scope">
            <el-input v-model="scope.row.materialNo"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="specifications"
          label="规格"
          width="150"
          min-width="150"
        >
          <template #default="scope">
            <el-input v-model="scope.row.specifications"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="model"
          label="型号"
          width="150"
          min-width="150"
        >
          <template #default="scope">
            <el-input v-model="scope.row.model"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="quantity"
          label="数量"
          width="150"
          min-width="150"
        >
          <template #default="scope">
            <el-input v-model="scope.row.quantity"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="controlCategory"
          label="控制类别"
          width="150"
          min-width="150"
        >
          <template #default="scope">
            <el-input v-model="scope.row.controlCategory"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="selfMadeCategory"
          label="自制类别"
          width="150"
          min-width="150"
        >
          <template #default="scope">
            <el-input v-model="scope.row.selfMadeCategory"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="remark"
          label="备注"
          min-width="220"
        >
          <template #default="scope">
            <el-input v-model="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          fixed="right"
          fit
          width="80"
          min-width="60"
        >
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              icon="delete"
              @click="deleteRowSubMaterialTable(scope.$index)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </receipt-core>
</template>

<script lang="ts" setup>
import ReceiptCore from "@/components/receipt/ReceiptCore.vue";
import { defineProps, provide, ref, withDefaults } from "vue";
import { ReceiptsSub } from "@/models/ReceiptsSub";
import { SelectedPropMap } from "@/components/input/SelectedPropMap";
import { AutocompleteInputEvent } from "@/components/input/AutocompleteInputEvent";
import AutocompleteInput from "@/components/input/AutocompleteInput.vue";
import { AutocompleteInputEventArray } from "@/components/input/AutocompleteInputEventArray";
import api from "@/utils";
import { OrderReceiptsSubMaterial } from "@/models/OrderReceiptsSubMaterial";
import { ElMessage, ElMessageBox } from "element-plus/es";

const props = withDefaults(defineProps<ReceiptsProps>(), {
  approveName: "",
});

export interface ReceiptsProps {
  approveName: string;
}

//传递到单据表中需要展示的列到ReceiptsTable
const receiptsTableFieldList = [
  {
    filedName: "approveStatus",
    label: "审批状态",
    width: 280,
  },
  {
    filedName: "idJson.customerName",
    label: "客户名称",
    width: 220,
  },
  {
    filedName: "idJson.preparationPerson",
    label: "编制人",
    width: 220,
  },
  {
    filedName: "idJson.preparationDate",
    label: "编制日期",
    width: 220,
  },
  {
    filedName: "idJson.unitLeader",
    label: "单位负责人",
    width: 220,
  },
  {
    filedName: "idJson.auditor",
    label: "审核人",
    width: 220,
  },
  {
    filedName: "idJson.reviewer",
    label: "复核人",
    width: 220,
  },
];
provide("receiptsTableFieldList", receiptsTableFieldList);

// 数据规范, 表中没有需要规范格式的数据, 则不需要这一行.
const dataFormat = (
  columnName: string,
  cellValue: string,
  callback: (value: string) => void
) => {
  if (columnName === "idJson.preparationDate") {
    const date = new Date(cellValue);
    const dateFormat = api.formatDate(date, "yyyy年MM月dd日");
    if (dateFormat !== "NaN年aN月aN日") {
      callback(dateFormat);
    }
  }
};
//传递idJson内的内容ReceiptsCore的Dialog内的插槽
const idJsonItems = ref({
  customerName: null,
  preparationPerson: null,
  preparationDate: null,
  unitLeader: null,
  auditor: null,
  reviewer: null,
} as unknown);
provide("idJsonItems", idJsonItems);

//传递subJson内的内容到ReceiptsCore的Dialog内的Table内的插槽
const subJsonItems = ref([
  {
    homemadeName: null,
    model: null,
    quantity: null,
    unit: null,
    completedQuantity: null,
    expectedDeliveryDate: null,
    constructionSection: null,
    actualDeliveryDate: null,
  },
] as Array<unknown>);
// provide("subJsonItems", subJsonItems);

const OrderReceiptSubMaterial = ref([{}] as Array<OrderReceiptsSubMaterial>);
const OrderReceiptSubMaterialNo = ref("" as string);
const OrderReceiptSubMaterialItemNo = ref("" as string);
//传递subJson内的内容到ReceiptsCore的Dialog内的Table内的插槽
const subJsonDetailsItems = ref({
  homemadeName: null,
  model: null,
  quantity: null,
  unit: null,
  completedQuantity: null,
  expectedDeliveryDate: null,
  constructionSection: null,
  actualDeliveryDate: null,
} as unknown);
// provide("subJsonItems", subJsonItems);

//清空传递idJson内的内容ReceiptsCore的Dialog内的插槽内容
//清空传递subJson内的内容ReceiptsCore的Dialog内的Table内的插槽内容
//远程搜索的数据除外，不用清除，不然无法使用远程搜索
const clearOpenJson = () => {
  idJsonItems.value = {
    preparationPerson: null,
    preparationDate: null,
    unitLeader: null,
    auditor: null,
    reviewer: null,
  };
  subJsonItems.value = [
    {
      model: null,
      quantity: null,
      unit: null,
      completedQuantity: null,
      expectedDeliveryDate: null,
      constructionSection: null,
      actualDeliveryDate: null,
    },
  ];
};

//子组件编辑时将某行idJson传递回本父组件并导入插槽内
//子组件编辑时将某行receiptsSub传递回本父组件，然后取出subJson导入插槽内
const poseEditJson = (idJson: unknown, receiptsSub?: Array<ReceiptsSub>) => {
  idJsonItems.value = idJson;
  subJsonItems.value = [];
  if (!(receiptsSub?.length === undefined || receiptsSub?.length === 0)) {
    for (let i = 0; i < receiptsSub.length; i = i + 1) {
      subJsonItems.value.push({});
      subJsonItems.value[i] = receiptsSub[i].subJson;
    }
  }
};

//子组件展开细节时将某子表行subJson传递回本父组件
const poseSubDetailsEditJson = (
  subJsonRow: unknown,
  no: string,
  itemNo: string
) => {
  OrderReceiptSubMaterialNo.value = no;
  OrderReceiptSubMaterialItemNo.value = itemNo;
  if (subJsonRow !== undefined) {
    subJsonDetailsItems.value = subJsonRow;
  }
  api.http
    .getJson(
      "/receipts/orderReceiptSubMaterial/orderReceiptSubMaterial/" +
        no +
        "/" +
        itemNo
    )
    .then((res) => {
      OrderReceiptSubMaterial.value = res.data;
    })
    .catch((err) => {
      console.log(err);
    });
};
provide("refreshPoseSubDetailsEditJson", poseSubDetailsEditJson);

//子组件展开细节提交保存
const submitOrderMaterial = () => {
  console.log(OrderReceiptSubMaterial.value);
  api.http
    .postJson(
      "/receipts/orderReceiptSubMaterial/orderReceiptSubMaterial/submit/" +
        OrderReceiptSubMaterialNo.value +
        "/" +
        OrderReceiptSubMaterialItemNo.value,
      OrderReceiptSubMaterial.value
    )
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });
};
provide("submitOrderMaterial", submitOrderMaterial);

//提交表单时将最新的ReceiptsSub传来处理，加入subJson后用callback返回
const poseSubmitJson = (
  callback: (value: Array<ReceiptsSub>) => void,
  no: string,
  receiptsSub: Array<ReceiptsSub>
) => {
  if (receiptsSub?.length === 0) {
    subJsonItems.value = [];
  } else {
    let i = 0;
    for (i; i < receiptsSub.length; i = i + 1) {
      receiptsSub[i].subJson = subJsonItems.value[i];
      receiptsSub[i].no = no;
    }
  }
  callback(receiptsSub);
};

const addRowSub = () => {
  subJsonItems.value.push({});
};
const deleteRowSub = (index: number) => {
  subJsonItems.value.splice(index, 1);
};
const jsonFormat = (
  data: Record<string, unknown>[][],
  callback: (value: Record<string, unknown>[]) => void
) => {
  let jsonList: Record<string, unknown>[] = [];
  for (let i = 0; i < data[0].length; i++) {
    // 存入字段名和excel表中的名称的映射，记得修改
    jsonList[i] = {};
    jsonList[i].no = data[0][i]["test1"];
    jsonList[i].name = data[0][i]["test2"];
    jsonList[i].description = data[0][i]["test3"];
    jsonList[i].departmentPhone = data[0][i]["test4"];
    jsonList[i].createUser = sessionStorage.getItem("token") as string;
    jsonList[i].createGmt = new Date();
  }
  callback(jsonList);
};
const deleteRowSubMaterialTable = (index: number) => {
  ElMessageBox.confirm("确认删除本行记录吗？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    if (OrderReceiptSubMaterial.value.length > 1) {
      OrderReceiptSubMaterial.value?.splice(index, 1);
    } else {
      ElMessage({
        message: "已经不能再少了",
        type: "warning",
      });
    }
  });
};
const addRowSubMaterial = () => {
  OrderReceiptSubMaterial.value?.push({
    no: OrderReceiptSubMaterialNo.value,
    itemNo: OrderReceiptSubMaterialItemNo.value,
  });
};
/**
 * 远程搜索和名称跟随
 */
const selectedPropMap = {
  selectedProp: "customerName",
  selectedOriginProp: "name",
  setProp: "contractName",
  setOriginProp: "name",
} as SelectedPropMap;

const { getRecords } = AutocompleteInputEvent(
  "/basic-request/Customer",
  idJsonItems,
  selectedPropMap
);

//多个远程搜索用类接收返还，用.属性调用。
//涉及数组时，用封装的数组专用组件，用getRecords完成选择框的内容，返回想要的某个对象，再在本vue内完成赋值。
const selectedPropMapSub = {
  selectedProp: "homemadeName",
  selectedOriginProp: "name",
  setProp: "homemadeName",
  setOriginProp: "name",
} as SelectedPropMap;
const autocompleteInputEventSub = AutocompleteInputEventArray(
  "/basic-request/Homemade",
  selectedPropMapSub
);
</script>

<style scoped></style>
